package org.anderground.editor.gui.properties.line;

import java.awt.Component;

import javax.swing.AbstractCellEditor;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;

import org.anderground.core.model.Line;
import org.anderground.editor.gui.properties.AbstractPropertiesPanel;

public abstract class AbstractStringLineProperty implements
		AbstractPropertiesPanel.Property {
	@Override
	public TableCellEditor getCellEditor() {
		return new MyCellEditor();
	}

	protected abstract void setValue(Line line, String cellEditorValue);

	protected abstract String getValue(Line line);

	@Override
	public TableCellRenderer getCellRender() {

		return new TableCellRenderer() {

			@Override
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column) {
				String text = getValue((Line) value);
				return new JLabel(text);
			}

		};
	}

	@SuppressWarnings("serial")
	class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
		private JTextField text = new JTextField();
		private Line currenLine;

		public MyCellEditor() {
			this.addCellEditorListener(new CellEditorListener() {
				@Override
				public void editingCanceled(ChangeEvent e) {
				}

				@Override
				public void editingStopped(ChangeEvent e) {
					setValue(currenLine, (String) getCellEditorValue());
				}

			});
		}

		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			currenLine = (Line) value;
			text.setText(getValue(currenLine));
			return text;
		}

		@Override
		public Object getCellEditorValue() {
			return text.getText();
		}

	};

}
